package com.ingrun.tuboshu.config;

import cn.dev33.satoken.exception.SaTokenException;
import com.ingrun.tuboshu.utils.Response;
import com.ingrun.tuboshu.utils.ResponseEnum;
import com.ingrun.tuboshu.utils.ResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author fxsz
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(ResponseException.class)
    public Response<String> handleResultException(ResponseException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址： '{}', 错误信息： '{}'", requestURI, e.getMessage(), e);
        return Response.error(e);
    }

    @ExceptionHandler(SaTokenException.class)
    public Response<String> handleResultException(SaTokenException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址： '{}', 错误信息： '{}'", requestURI, e.getMessage(), e);
        return Response.error(ResponseEnum.UNAUTHORIZED);
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response<HttpStatus> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                                    HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return Response.error(HttpStatus.METHOD_NOT_ALLOWED, e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Response<HttpStatus> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return Response.error(HttpStatus.BAD_REQUEST, e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Response<HttpStatus> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return Response.error(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
